<template>
  <div class="goods-add-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-page-header @back="goBack">
            <template #content>新增商品</template>
          </el-page-header>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="goods-form"
        label-position="right">
        <el-form-item label="商品名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入商品名称" 
            clearable />
        </el-form-item>

        <el-form-item label="商品分类" prop="category">
          <el-select 
            v-model="form.category" 
            placeholder="请选择分类"
            clearable>
            <el-option label="手机数码" value="1" />
            <el-option label="家用电器" value="2" />
            <el-option label="电脑办公" value="3" />
            <el-option label="服装配饰" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="0.1"
            controls-position="right"
            style="width: 200px"
          />
          <span class="unit">元</span>
        </el-form-item>

        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            :precision="0"
            controls-position="right"
            style="width: 200px"
          />
          <span class="unit">件</span>
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="goods-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="customUpload"
            accept="image/jpeg,image/png">
            <img v-if="form.image" :src="form.image" class="goods-image" />
            <el-icon v-else class="goods-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            只能上传 jpg/png 文件，且不超过 2MB
          </div>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
            size="large">
            提交
          </el-button>
          <el-button 
            @click="goBack"
            size="large">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

const form = reactive({
  name: '',
  category: '',
  price: 0,
  stock: 0,
  image: '',
  description: '',
  status: 1
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, message: '描述至少需要10个字符', trigger: 'blur' }
  ]
}

const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await request({
      url: '/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    form.image = res.data.url
    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await request({
          url: '/goods',
          method: 'post',
          data: form
        })
        ElMessage.success('添加成功')
        goBack()
      } catch (error) {
        console.error('添加商品失败:', error)
        ElMessage.error('添加商品失败')
      } finally {
        loading.value = false
      }
    }
  })
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>



.goods-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
}

.goods-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.goods-uploader:hover {
  border-color: #409EFF;
}

.goods-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.goods-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: contain;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.el-form-item:last-child {
  margin-top: 30px;
  text-align: center;
}
</style>